package cn.com.inossem.activity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;

/**
 * 
 * 八卦设置
 * 
 * <p>
 * detailed comment
 * 
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
public class BaGuaSheZhiActivity extends RequestActivity {

	// 展示图片
	private Integer[] mThumbIds = { R.drawable.h1, R.drawable.h2,
			R.drawable.h3, R.drawable.h4, R.drawable.h5, R.drawable.h6,
			R.drawable.h7, R.drawable.h8, R.drawable.h9, R.drawable.h10,
			R.drawable.h11, R.drawable.h12, R.drawable.h13, R.drawable.h14,
			R.drawable.h15, R.drawable.h16, };

	ImageView xuanzhongpic, back;
	TextView huaming, changename, shezhi;
	Button suiji;
	public List<TextView> listview;
	List<String> nicknameList = new ArrayList<String>(10);
	private String selectedNickname, selectedPicName;
	private int selectedPosition = -1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main_tab_layout);
		getInfo();
		initView();

		GridView gridView = (GridView) findViewById(R.id.gridview);
		gridView.setAdapter(new ImageAdapter(this));
		// 单击GridView元素的响应
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 弹出单击的GridView元素的位置
				// Toast.makeText(BaGuaSheZhiActivity.this, mThumbIds[position],
				// Toast.LENGTH_SHORT).show();
				selectedPicName = "h" + (position + 1);
//				setInfo("picname", "h" + (position + 1));
				xuanzhongpic.setBackgroundResource(mThumbIds[position]);
			}
		});
	}

	private void setInfo(String key, String value) {
		// 获得SharedPreferences对象
		SharedPreferences settings = this.getSharedPreferences("shared_file",
				Activity.MODE_PRIVATE);

		// 获得可编辑对象
		SharedPreferences.Editor editor = settings.edit();

		editor.putString(key, value);

		editor.commit();
	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		listview = new ArrayList<TextView>();
		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);

		xuanzhongpic = (ImageView) this.findViewById(R.id.xuanzhongpic);
//		System.out.println("picname:" + picname);
//		xuanzhongpic.setBackgroundResource(getResource(picname));
		
		LinearLayout linlayer1 = (LinearLayout) this.findViewById(R.id.linlayer1);
		addView(linlayer1);

		huaming = (TextView) this.findViewById(R.id.huaming);
		huaming.setText("花名：" + name);
		suiji = (Button) this.findViewById(R.id.suiji);
		suiji.setOnClickListener(this);
		suiji.setVisibility(View.GONE);
		
		changename = (TextView) this.findViewById(R.id.changename);
		changename.setOnClickListener(this);
		
		shezhi = (TextView) this.findViewById(R.id.shezhi);
		shezhi.setOnClickListener(this);
	}
	
	private void getNicknameList() {
		Set<Integer> existNumSet = new HashSet<Integer>(10);
		for (int i = 0; i < 10; i++) {
			int random = (int) (Math.random() * Utils.niming.length);
			if (!existNumSet.add(random))
				continue;
			nicknameList.add(Utils.niming[random]);
			if (!listview.isEmpty()) {
				listview.get(i).setTextColor(Color.rgb(66, 66, 66));
				listview.get(i).setBackgroundResource(R.drawable.weixuanzhong);
				listview.get(i).setText(Utils.niming[random]);
			}
		}
	}
	
	private void addView(LinearLayout layer) {
		getNicknameList();
		List<TextView> listText = new ArrayList<TextView>();
		LayoutInflater mInflater;
		List<View> listtextview = new ArrayList<View>();
		for (int i = 0; i < nicknameList.size(); i++) {
			mInflater = LayoutInflater.from(this);
			View view = mInflater.inflate(R.layout.textviewitem, null);
			String text = nicknameList.get(i);
			TextView textview = (TextView) view.findViewById(R.id.textview);
			textview.setTextColor(Color.rgb(66, 66, 66));
			textview.setBackgroundResource(R.drawable.weixuanzhong);
			textview.setText(text);
			textview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (selectedPosition != -1) {
						TextView selectedTV = listview.get(selectedPosition);
						selectedTV.setTextColor(Color.rgb(66, 66, 66));
						selectedTV.setBackgroundResource(R.drawable.weixuanzhong);
					}
					TextView tv = (TextView) v;
					tv.setBackgroundResource(R.drawable.xuanzhong);
					tv.setTextColor(Color.rgb(255, 255, 255));
					selectedNickname = String.valueOf(tv.getText());
					int posion = (Integer) tv.getTag();
					selectedPosition = posion;
//					setInfo("name", String.valueOf(tv.getText()));
				}
			});
			Paint paint = new Paint();
			paint.setTextSize(textview.getTextSize());
			float size = paint.measureText(textview.getText().toString());
			view.setTag((int) size + Utils.dip2px(this, 10 * 2 + 10));
			textview.setTag(i);
			listText.add(textview);
			listtextview.add(view);
			listview.add(textview);
		}
//		listview.add(listText);

		int j = 0;
		LinearLayout llayout = null;
		int MaxWidth = MainActivity.widthPixels - Utils.dip2px(this, 20);
		int temporarywidth = 0;
		while (true) {
			View view = null;
			int tagwidth = 0;
			if (j == listtextview.size()) {
				return;
			} else {
				view = listtextview.get(j);
				tagwidth = (Integer) view.getTag();
			}
			if (j == 0) {
				llayout = new LinearLayout(this);
			}
			System.out.println("textview:" + tagwidth + "temporarywidth:" + temporarywidth + "MaxWidth:" + MaxWidth);
			if (tagwidth + temporarywidth + 40 < MaxWidth) {
				temporarywidth += tagwidth;
				llayout.addView(view);
			} else {
				layer.addView(llayout);

				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(0, 15, 0, 0);

				llayout = new LinearLayout(this);
				llayout.setLayoutParams(layoutParams);
				temporarywidth = (Integer) view.getTag();

				llayout.addView(view);
			}

			if (j == listtextview.size() - 1) {
				layer.addView(llayout);
			}
			j++;
		}
	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {

	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.baguashezhi_layout;

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.suiji:
			int random = (int) (Math.random() * Utils.niming.length);
			setInfo("name", Utils.niming[random]);
			huaming.setText("花名：" + Utils.niming[random]);
			break;
		case R.id.changename:
			getNicknameList();
			selectedPosition = -1;
			break;
		case R.id.shezhi:
			if ((selectedNickname == null) || (selectedPicName == null)) {
				Toast.makeText(this, "花名或头像不能为空！", Toast.LENGTH_LONG).show();
				return;
			}
			setInfo("name", selectedNickname);
			setInfo("picname", selectedPicName);
			finish();
			break;
		default:
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 1:
			setResult(1);
			finish();
		default:
			break;
		}
	}

	private class ImageAdapter extends BaseAdapter {
		private Context mContext;

		public ImageAdapter(Context context) {
			this.mContext = context;
		}

		@Override
		public int getCount() {
			return mThumbIds.length;
		}

		@Override
		public Object getItem(int position) {
			return mThumbIds[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// 定义一个ImageView,显示在GridView里
			ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(Utils
						.dip2px(mContext, 40), Utils.dip2px(mContext, 40)));
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				imageView.setPadding(8, 8, 8, 8);
			} else {
				imageView = (ImageView) convertView;
			}
			imageView.setImageResource(mThumbIds[position]);
			return imageView;
		}

	}

	String picname = "";
	String name = "";

	private void getInfo() {
		SharedPreferences settings = this
				.getSharedPreferences("shared_file", 0);

		int random = (int) (Math.random() * Utils.niming.length);
		name = settings.getString("name", Utils.niming[random]);
		int picrandom = 1 + (int) (Math.random() * 16);
		picname = settings.getString("picname", "h" + picrandom);

		System.out.println("picname::::::" + picname);
		boolean ishuaming = settings.getBoolean("ishuaming", true);
	}

	/**
	 * 获取图片名称获取图片的资源id的方法
	 * 
	 * @param imageName
	 * @return
	 */
	public int getResource(String imageName) {
		int resId = getResources().getIdentifier(imageName, "drawable",
				getPackageName());
		return resId;
	}
}
